﻿using System;
using System.Collections.Generic;
using System.Linq;
using Colligate;

namespace OrgDataSource
{
// ReSharper disable InconsistentNaming
    public class MemberDS:IOrgDS
// ReSharper restore InconsistentNaming
    {
        #region\\delete
        public int DeleteTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context)
        {
            switch (dataType.ToLower())
            {
                case "member": return DeleteMember(dataGuid, context);
                default: throw new Exception("MemberDS无法处理该" + dataType + "的数据");
            }
        }

        private static int DeleteMember(string dataGuid, orgEntities context)
        {
            System.Data.Common.DbTransaction trans = null;
            try
            {
                context.Connection.Open();
                trans = context.Connection.BeginTransaction();
                var member = context.Member.FirstOrDefault(cc => cc.Guid == dataGuid);
                var account = context.Account.FirstOrDefault(cc => cc.Guid == dataGuid);
                context.DeleteObject(member);
                context.DeleteObject(account);
                context.SaveChanges();
                trans.Commit();
                return 0;
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw new Exception("删除数据标识为：" + dataGuid + "的Member数据时出错！");
            }
            finally
            {
                context.Connection.Close();
            }
        }
        #endregion
        #region\\get
        public System.Xml.XmlNode GetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, orgEntities context, BaseTaskDataSource baseInfo)
        {
            switch (dataType.ToLower())
            {
                case "member": return GetMember(dataGuid, context);
                case "membergrouplist": return GetMemberGroupList(dataGuid, context);
                case "usertasklist": return GetUserTaskList(dataGuid, context, baseInfo);
                case "memberdetail": return GetMemberDetail(dataGuid, context);
                case "memberrolelist": return GetMemberRoleList(dataGuid, context);
                default: throw new Exception("MemberDS无法处理该" + dataType + "的数据");
            }
        }

        private static System.Xml.XmlNode GetMember(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "Member");
                var member = context.Member.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new Member
                                                                                             {
                                                                                                 Guid = string.Empty,
                                                                                                 Name = string.Empty,
                                                                                                 BranchGuid = string.Empty,
                                                                                                 Telephone = string.Empty,
                                                                                                 Handphone1 = string.Empty,
                                                                                                 Handphone2 = string.Empty,
                                                                                                 EMail = string.Empty,
                                                                                                 Sort = null
                                                                                             };
                XmlNodeManage.SetSubValue(result, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Guid);
                XmlNodeManage.SetSubValue(result, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Name);
                XmlNodeManage.SetSubValue(result, "BranchGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.BranchGuid);
                XmlNodeManage.SetSubValue(result, "Telephone", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Telephone);
                XmlNodeManage.SetSubValue(result, "Handphone1", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Handphone1);
                XmlNodeManage.SetSubValue(result, "Handphone2", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Handphone2);
                XmlNodeManage.SetSubValue(result, "EMail", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.EMail);
                XmlNodeManage.SetSubValue(result, "Order", Enum.GetName(typeof(TypeEnum), TypeEnum.LONG), member.Sort);
                return result;
            }
            catch
            {
                throw new Exception("获取数据标识为：" + dataGuid + "的Member数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetMemberGroupList(string dataGuid, orgEntities context)
        {
            try
            {
                var companyList = context.Company.ToList();
                var branchList = context.Branch.ToList();
                var groupList = context.Group.ToList();
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "MemberGroupList");
                var subNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                var groupMember =
                    context.GroupMember.Where(
                        cc =>
                        (cc.Type.ToLower().Equals("company") || cc.Type.ToLower().Equals("branch") ||
                         cc.MemberGuid == dataGuid) && cc.Status == "true");
                foreach (var item in groupMember)
                {
                    if(item.Type.ToLower().Equals("company"))
                    {
                        var company = companyList.FirstOrDefault(cc => cc.Guid == dataGuid);
                        if (null == company)
                            continue;
                        if (!dataGuid.Equals(company.EventerGuid))
                            continue;
                    }
                    if (item.Type.ToLower().Equals("branch"))
                    {
                        var branch = branchList.FirstOrDefault(cc => cc.Guid == dataGuid);
                        if (null == branch)
                            continue;
                        if (!dataGuid.Equals(branch.LeaderGuid))
                            continue;
                    }
                    var childNode = XmlNodeManage.CreateNode("OUDataInfo");
                    XmlNodeManage.SetSubValue(childNode, "@GUID", item.GroupGuid);
// ReSharper disable AccessToModifiedClosure
                    XmlNodeManage.SetSubValue(childNode, "@NAME", groupList.FirstOrDefault(cc => cc.Guid == item.GroupGuid).Name);
// ReSharper restore AccessToModifiedClosure
                    XmlNodeManage.SetSubValue(childNode, "@OUType", "Group");
                    XmlNodeManage.SetSubValue(childNode, "@CompanyGuid", item.GroupGuid);
                    subNode.AppendChild(childNode);
                }
                result.AppendChild(subNode);
                return result;
            }
            catch
            {
                throw new Exception("获取的MemberGroupList数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetMemberRoleList(string dataGuid, orgEntities context)
        {
            try
            {
                //var companyList = context.Company.ToList();
                //var branchList = context.Branch.ToList();
                var roleList = context.Role.ToList();
                var tempList = new List<string>();
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "MemberRoleList");
                var subNode = XmlNodeManage.CreateNode("ListOUDataInfo");
                var memberRole =
                    context.RoleMember.Where(cc => cc.MemberId == dataGuid);
                foreach (var item in memberRole)
                {

                    if (tempList.Contains(item.RoleId))
                        continue;
                    var childNode = XmlNodeManage.CreateNode("OUDataInfo");
                    XmlNodeManage.SetSubValue(childNode, "@GUID", item.RoleId);
                    var nameStr = null == roleList.FirstOrDefault(cc => cc.Guid == item.RoleId)
                                   ? string.Empty
                                   : roleList.FirstOrDefault(cc => cc.Guid == item.RoleId).Name;
                    XmlNodeManage.SetSubValue(childNode, "@NAME", nameStr);
                    XmlNodeManage.SetSubValue(childNode, "@OUType", "Role");
                    XmlNodeManage.SetSubValue(childNode, "@CompanyGuid", string.Empty);
                    subNode.AppendChild(childNode);
                    tempList.Add(item.RoleId);
                }
                result.AppendChild(subNode);
                return result;
            }
            catch
            {
                throw new Exception("获取的MemberRoleList数据时出错！");
            }
        }

        private static System.Xml.XmlNode GetUserTaskList(string dataGuid, orgEntities context, BaseTaskDataSource baseInfo)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "UserTaskList");
                var task = context.WorkTask.Where(cc => cc.Status == "true").OrderBy(cc => cc.TaskType).OrderBy(cc => cc.Sort).ToList();
                
                foreach (var item in task)
                {
                    if (null != item.TaskMember && item.TaskMember.Count != 0)
                    {
                        if (GetTaskList(dataGuid, item.TaskMember, context))
                            BuildSubNode(item, result);
                    }
                    else
               
                        BuildSubNode(item, result);
                }
                return result;
            }
            catch
            {
                throw new Exception("获取的UserTaskList数据时出错！");
            }
        }
        private static System.Xml.XmlNode GetMemberDetail(string dataGuid, orgEntities context)
        {
            try
            {
                var result = XmlNodeManage.GetDocumentNode(Utility.GetTaskGuid(), dataGuid, "MemberDetail");
                var account = context.Account.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new Account
                                                                                               {
                                                                                                   Guid = string.Empty,
                                                                                                   AccountName =
                                                                                                       string.Empty,
                                                                                                   Type = string.Empty,
                                                                                                   Name = string.Empty,
                                                                                                   Password =
                                                                                                       string.Empty,
                                                                                                   IsEvection =
                                                                                                       string.Empty,
                                                                                                   Status = string.Empty

                                                                                               };

                var member = context.Member.FirstOrDefault(cc => cc.Guid == dataGuid) ?? new Member
                {
                    Guid = string.Empty,
                    Name = string.Empty,
                    BranchGuid = string.Empty,
                    Telephone = string.Empty,
                    Handphone1 = string.Empty,
                    Handphone2 = string.Empty,
                    EMail = string.Empty,
                    Sort = null
                };
                var branch = context.Branch.FirstOrDefault(cc => cc.Guid == member.BranchGuid);
                string leader;
                if (null != branch)
                {
                    var tempMember = context.Member.FirstOrDefault(cc => cc.Guid == branch.LeaderGuid);
                    leader = null == tempMember ? string.Empty : tempMember.Name;
                }
                else
                    leader = string.Empty;
                var groupList = GetMemberGroupList(dataGuid, context);
                var roleList = GetMemberRoleList(dataGuid, context);
                XmlNodeManage.SetSubValue(result, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.GUID), member.Guid);
                XmlNodeManage.SetSubValue(result, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Name);
                XmlNodeManage.SetSubValue(result, "Account", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), account.AccountName);
                XmlNodeManage.SetSubValue(result, "Branch", Enum.GetName(typeof (TypeEnum), TypeEnum.TEXT),
                                          null == branch ? string.Empty : branch.Name);
                XmlNodeManage.SetSubXML(result, "MemberGroupList", groupList.InnerXml);
                XmlNodeManage.SetSubXML(result, "MemberRoleList", roleList.InnerXml);
                XmlNodeManage.SetSubValue(result, "Leader", Enum.GetName(typeof(TypeEnum), TypeEnum.LONG), leader);
                XmlNodeManage.SetSubValue(result, "IsEvection", Enum.GetName(typeof(TypeEnum), TypeEnum.LOGICAL), account.IsEvection);
                XmlNodeManage.SetSubValue(result, "Telephone", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Telephone);
                XmlNodeManage.SetSubValue(result, "Handphone1", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Handphone1);
                XmlNodeManage.SetSubValue(result, "Handphone2", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.Handphone2);
                XmlNodeManage.SetSubValue(result, "EMail", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT), member.EMail);
                XmlNodeManage.SetSubValue(result, "Order", Enum.GetName(typeof(TypeEnum), TypeEnum.LONG), member.Sort);
                return result;
            }
            catch
            {
                throw new Exception("获取数据标识为：" + dataGuid + "的MemberDetail数据时出错！");
            }
        }
        private static bool GetTaskList(string dataGuid, IEnumerable<TaskMember> tm, orgEntities context)
        {
            try
            {
                foreach (var item in tm)
                {
                    switch (item.Type.ToLower().Trim())
                    {
                        case "company":
                            if(GetCompanyTask(dataGuid, item.MemberId, context))
                                return true;
                            continue;
                        case "branch":
                            if (GetBranchTask(dataGuid, item.MemberId, context))
                                return true;
                            continue;
                        case "member":
                            if (GetMemberTask(dataGuid, item.MemberId))
                                return true;
                            continue;
                        case "group":
                            if (GetGroupTask(dataGuid, item.MemberId, context))
                                return true;
                            continue;
                        default: continue;
                    }
                }
                return false;
            }
            catch
            {
                return false;
            }
        }
        private static bool GetCompanyTask(string dataGuid, string memberGuid, orgEntities context)
        {
            var company = context.Company.FirstOrDefault(cc => cc.Guid == memberGuid && cc.EventerGuid.Trim().Equals(dataGuid));
            return null != company;
        }
        private static bool GetBranchTask(string dataGuid, string memberGuid, orgEntities context)
        {
            var branch = context.Branch.FirstOrDefault(cc => cc.Guid == memberGuid && cc.LeaderGuid.Trim().Equals(dataGuid));
            return null != branch;
        }
        private static bool GetMemberTask(string dataGuid, string memberGuid)
        {
            return memberGuid.Trim().Equals(dataGuid);
        }
        private static bool GetGroupTask(string dataGuid, string memberGuid, orgEntities context)
        {
            var groupMember = context.GroupMember.FirstOrDefault(cc => cc.GroupGuid == memberGuid && cc.MemberGuid.Trim().Equals(dataGuid));
            return null != groupMember;
        }
        private static void BuildSubNode(WorkTask task, System.Xml.XmlNode result)
        {
            var subNode = XmlNodeManage.CreateNode("UserTaskList");
            XmlNodeManage.SetSubValue(subNode, "Guid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT),
                                      task.Guid);
            XmlNodeManage.SetSubValue(subNode, "Name", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT),
                                      task.Name);
            XmlNodeManage.SetSubValue(subNode, "AppGuid", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT),
                                      task.AppGuid);
            XmlNodeManage.SetSubValue(subNode, "TaskType", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT),
                                      task.TaskType);
            XmlNodeManage.SetSubValue(subNode, "Icon", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT),
                                      task.Icon);
            XmlNodeManage.SetSubValue(subNode, "Status", Enum.GetName(typeof(TypeEnum), TypeEnum.TEXT),
                                      task.Status);
            result.AppendChild(subNode);
        }

        #endregion
        #region\\set
        public int SetTaskData(OUDataInfo userInfo, string dataGuid, string dataType, System.Xml.XmlNode xmlData, orgEntities context)
        {
            var datatype = XmlNodeManage.GetSubValue(xmlData, "@DataType");
            switch (datatype.ToLower())
            {
                case "member": return SetMember(xmlData, context);
                default: throw new Exception("MemberDS无法处理该" + datatype + "的数据");
            }
        }

        private static int SetMember(System.Xml.XmlNode xmlData, orgEntities context)
        {
            System.Data.Common.DbTransaction trans = null;
            try
            {
                context.Connection.Open();
                trans = context.Connection.BeginTransaction();
                var id = Utility.CheckXmlData(xmlData, "Guid");
                var member = context.Member.FirstOrDefault(cc => cc.Guid == id);
                if (null == member)
                {
                    member = new Member
                                 {
                                     Guid = id,
                                     BranchGuid = Utility.CheckXmlData(xmlData, "BranchGuid"),
                                     EMail = Utility.CheckXmlData(xmlData, "EMail"),
                                     Telephone = Utility.CheckXmlData(xmlData, "Telephone"),
                                     Handphone1 = Utility.CheckXmlData(xmlData, "Handphone1"),
                                     Handphone2 = Utility.CheckXmlData(xmlData, "Handphone2"),
                                     Name = Utility.CheckXmlData(xmlData, "Name"),
                                     Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order"))
                                 };
                    var account = new Account
                                      {
                                          Guid = id,
                                          IsEvection = "false",
                                          Name = member.Name,
                                          Password = "123456",
                                          Status = "true",
                                          Type = "Member",
                                          AccountName = member.EMail.Substring(0, member.EMail.IndexOf('@'))
                                      };
                    context.AddToMember(member);
                    context.AddToAccount(account);
                }
                else
                {
                    member.BranchGuid = Utility.CheckXmlData(xmlData, "BranchGuid");
                    member.EMail = Utility.CheckXmlData(xmlData, "EMail");
                    member.Telephone = Utility.CheckXmlData(xmlData, "Telephone");
                    member.Handphone1 = Utility.CheckXmlData(xmlData, "Handphone1");
                    member.Handphone2 = Utility.CheckXmlData(xmlData, "Handphone2");
                    member.Name = Utility.CheckXmlData(xmlData, "Name");
                    member.Sort = int.Parse(Utility.CheckXmlData(xmlData, "Order"));
                }
                context.SaveChanges();
                trans.Commit();
                return 0;
            }
            catch
            {
                if (trans != null)
                    trans.Rollback();
                throw new Exception("写入Member数据时出错！");
            }
            finally
            {
                context.Connection.Close();
            }
        }
        #endregion
        #region\\transform
        public System.Xml.XmlNode TransformTaskData(OUDataInfo userInfo, System.Xml.XmlNode xmlParam, orgEntities context, BaseTaskDataSource baseInfo)
        {
            throw new NotImplementedException();
        }
        #endregion
    }
}
